package com.chen.palmar.project.init;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chen.palmar.R;
import com.chen.palmar.base.CheckPermissionsFragment;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.BannerImageLoader;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.RoundImageView;
import com.chen.palmar.entity.AgencyListEntity;
import com.chen.palmar.entity.HomeBanEntity;
import com.chen.palmar.project.agency.AgencyDetailActivity;
import com.chen.palmar.project.agency.CityPickerActivity;
import com.chen.palmar.project.home.SearchListActivity;
import com.chen.palmar.project.set.ApplyAgencyActivity;
import com.orhanobut.logger.Logger;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zaaach.citypicker.CheckPermissionsListener;
import com.zaaach.citypicker.model.City;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

import static android.app.Activity.RESULT_OK;

/**
 * @author Chen
 * @date 2017/12/28
 * 功能描述：经销商
 */

public class AgencyFragment extends CheckPermissionsFragment implements CheckPermissionsListener {

    @Bind(R.id.et_search)
    TextView etSearch;
    @Bind(R.id.banner_view)
    Banner bannerView;
    @Bind(R.id.rv_last_info)
    RecyclerView rvLastInfo;
    @Bind(R.id.scroll_agency)
    NestedScrollView scrollAgency;
    @Bind(R.id.swipe_agency)
    SwipeRefreshLayout swipeAgency;
    @Bind(R.id.rb_agency_last)
    RadioButton rbAgencyLast;
    @Bind(R.id.rb_agency_near)
    RadioButton rbAgencyNear;
    @Bind(R.id.rg_agency_state)
    RadioGroup rgAgencyState;
    @Bind(R.id.tv_item_agency_city)
    TextView tvItemAgencyCity;
    @Bind(R.id.ly_agency_top)
    LinearLayout lyAgencyTop;
    private List<Object> images = new ArrayList<>();
    private BaseQuickAdapter<AgencyListEntity.DataBean, BaseViewHolder> adapter;
    public LocationClient mLocationClient = null;
    private static final int REQUEST_CODE_PICK_CITY = 2;
    private boolean isLocation = false;


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //注册事件
        EventBus.getDefault().register(this);
        initData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_agency;
    }

    @Override
    public void initData() {
        int statusBarHeight = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //获取status_bar_height资源的ID
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                Logger.v(statusBarHeight + "---");
                ViewGroup.LayoutParams params = lyAgencyTop.getLayoutParams();
                AutoLinearLayout.LayoutParams layoutParams = new AutoLinearLayout.LayoutParams(AutoLinearLayout.LayoutParams.MATCH_PARENT, AutoLinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(30, statusBarHeight + 25, 30, 25);
                lyAgencyTop.setLayoutParams(layoutParams);
            }
        }

        etSearch.requestFocus();

        etSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchListActivity.class);
                intent.putExtra("info", SearchListActivity.REQUEST_CODE_AGENCY);
                startActivity(intent);
            }
        });

        swipeAgency.setOnRefreshListener(() -> {
            try {
                if (tvItemAgencyCity.getTag() != null) {
                    getDataForWeb(tvItemAgencyCity.getTag().toString());
                } else {
                    getDataForWeb(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                swipeAgency.setRefreshing(false);
            }
        });
        swipeAgency.setRefreshing(true);
        swipeAgency.setColorSchemeColors(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright), ContextCompat.getColor(getContext(), android.R.color.holo_green_light), ContextCompat.getColor(getContext(), android.R.color.holo_orange_light), ContextCompat.getColor(getContext(), android.R.color.holo_red_light));


        //设置指示器位置（当banner模式中有指示器时）
        bannerView.setIndicatorGravity(BannerConfig.CENTER);
        bannerView.setImageLoader(new BannerImageLoader());

        rvLastInfo.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvLastInfo.setLayoutManager(linearLayoutManager);
        rvLastInfo.setItemAnimator(new DefaultItemAnimator());
        adapter = new BaseQuickAdapter<AgencyListEntity.DataBean, BaseViewHolder>(R.layout.item_agency) {
            @Override
            protected void convert(BaseViewHolder helper, AgencyListEntity.DataBean item) {
                helper.setText(R.id.tv_item_agency_name, item.getName());
                helper.setText(R.id.tv_item_agency_content, item.getDesc() + "");
                helper.setText(R.id.tv_item_agency_brand, "经营品牌：" + (TextUtils.isEmpty(item.getBrand()) ? "" : item.getBrand()));
                helper.setText(R.id.tv_item_agency_location, item.getAddress_name());
                helper.setText(R.id.tv_item_agency_distance, "");

                RoundImageView head = (RoundImageView) helper.getView(R.id.iv_item_agency);
                Picasso.with(getContext()).load(item.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);

                RecyclerView rvTag = (RecyclerView) helper.getView(R.id.rv_item_agency_tag);
                if (TextUtils.isEmpty(item.getChannel())) {
                    rvTag.setVisibility(View.GONE);
                } else {
                    rvTag.setVisibility(View.VISIBLE);
                    rvTag.setNestedScrollingEnabled(false);
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
                    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    rvTag.setLayoutManager(layoutManager);
                    BaseQuickAdapter<String, BaseViewHolder> adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_agency_tag) {
                        @Override
                        protected void convert(BaseViewHolder helper, String item) {
                            helper.setText(R.id.iv_item_tag, item);
                        }
                    };
                    rvTag.setItemAnimator(new DefaultItemAnimator());
                    String[] split = item.getChannel().split(" ");
                    adapterImg.setNewData(Arrays.asList(split));
                    rvTag.setAdapter(adapterImg);
                }
            }
        };
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), AgencyDetailActivity.class);
            intent.putExtra("info", adapter.getData().get(position).getDistrId() + "");
            startActivity(intent);
        });
        rvLastInfo.setAdapter(adapter);

        rbAgencyNear.setTextColor(ContextCompat.getColor(getContext(), R.color.app_font));
        rgAgencyState.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_agency_last:
                    rbAgencyLast.setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
                    rbAgencyNear.setTextColor(ContextCompat.getColor(getContext(), R.color.app_font));
                    break;
                case R.id.rb_agency_near:
                    rbAgencyNear.setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
                    rbAgencyLast.setTextColor(ContextCompat.getColor(getContext(), R.color.app_font));
                    break;
            }
        });

        try {
            getDataForWeb(null);
            getLocationCity();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
            swipeAgency.setRefreshing(false);
        }

        bannerView.setOnBannerListener(position -> {
            if (images.size() > 0) {
                HomeBanEntity.DataBean dataBean = (HomeBanEntity.DataBean) images.get(position);
                Intent intent = new Intent(getContext(), AgencyDetailActivity.class);
                intent.putExtra("info", dataBean.getRef_id() + "");
                startActivity(intent);
            }
        });
    }

    private void getLocationCity() {

        mLocationClient = new LocationClient(getContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation != null && !isLocation) {
                    String city = bdLocation.getCity();
                    if (!TextUtils.isEmpty(city)) {
                        isLocation = true;
                        tvItemAgencyCity.setText(city);
                    }
                }
            }
        });
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        option.setIsNeedLocationDescribe(true);
        option.setIsNeedAddress(true);

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        //请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mLocationClient.start();
        } else {
            requestPermissions(getActivity(), neededPermissions, this);
        }
    }

    private void getDataForWeb(String addressId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 2);
        if (addressId != null) {
            map.put("addressId", addressId);
        }
        Subscription subscribe = DataCenter.listAgencyInfo(map).subscribe(new HttpSubscriber<AgencyListEntity>(getContext(), null) {
            @Override
            public void onNext(AgencyListEntity agencyListEntity) {
                if (agencyListEntity.getData().size() == 0) {
                    showToast("该城市下暂无经销商");
                    return;
                }
                adapter.setNewData(agencyListEntity.getData());
                swipeAgency.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                swipeAgency.setRefreshing(false);
            }
        });
        subscription.add(subscribe);

        HashMap<String, String> mapBan = new HashMap<>();
        mapBan.put("type", "1");
        mapBan.put("position", "2");
        Subscription banSub = DataCenter.homeBanInfo(mapBan).subscribe(new HttpSubscriber<HomeBanEntity>(getContext(), null) {
            @Override
            public void onNext(HomeBanEntity homeEntity) {
                images.clear();
                images.addAll(homeEntity.getData());
                bannerView.setImages(images);
                bannerView.start();
            }
        });
        subscription.add(banSub);
    }

    @OnClick(R.id.tv_item_agency_city)
    public void onViewClicked() {
        startActivityForResult(new Intent(getContext(), CityPickerActivity.class), REQUEST_CODE_PICK_CITY);
    }

    //重写onActivityResult方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                City city = (City) data.getSerializableExtra(CityPickerActivity.KEY_PICKED_CITY);
                tvItemAgencyCity.setText(city.getName());
                tvItemAgencyCity.setTag(city.getAddessId());

                try {
                    getDataForWeb(city.getAddessId() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                    swipeAgency.setRefreshing(false);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventType()) {
            case ApplyAgencyActivity.EVENT_AGENCY_CODE:
                try {
                    getDataForWeb(null);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                    swipeAgency.setRefreshing(false);
                }
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mLocationClient.stop();
    }

    @Override
    public void onGranted() {
        mLocationClient.start();
    }

    @Override
    public void onDenied(List<String> permissions) {
        showToast("权限被禁用，无法定位");
        tvItemAgencyCity.setText("定位失败");
    }
}
